export * from '@ds/ds-micro-lib/dist';
import { ApplicationRef, enableProdMode, NgModuleFactory, NgModuleRef, ViewContainerRef } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
import { initStart, getSingleStore, lifeCycleCallBack } from '@ds/ds-micro-lib/dist';
import { defineCustomElements } from '@ds/ds-micro/dist/loader';
import { globalStore } from '@ds/ds-micro/dist';

if (environment.production) {
  enableProdMode();
}

let app: void | NgModuleRef<AppModule>;
async function render() {
  app = await platformBrowserDynamic()
    .bootstrapModule(AppModule)
    .catch(err => console.error(err));
}
initStart();

function getReplaceUrl(url: string) {
  return url ? url.replace(/https:\/\/|http:\/\//, '').replace(/\/|\-|\:|\./g, '_') : '';
}

function getAppUrl() {
  return getReplaceUrl(getSingleStore('systemData').value.id) + '_' + getReplaceUrl(getSingleStore('systemData').value.host);
}

lifeCycleCallBack({
  bootstrap: data => {
    render();
  },
  mount: data => {
    render();
    if (globalStore('cacheRouter')[getAppUrl()]) {
      console.log('==========================', globalStore('cacheRouter')[getAppUrl()]);
      const appRef: ApplicationRef = globalStore('cacheRouter')[getAppUrl()].injector.get(ApplicationRef);
      const elements = appRef.components.map(c => c.location.nativeElement);

      console.log('==========================', elements);
    }

    // if(globalStore('cacheRouter')[getAppUrl()]) {
    //   platformBrowserDynamic()
    //   .bootstrapModuleFactory(globalStore('cacheRouter')[getAppUrl()])
    //   .catch(err => console.error(err));

    // } else {
    // render();
    // }
  },
  unmount: () => {
    globalStore('cacheRouter')[getAppUrl()] = app;
    // @ts-ignore
    app.destroy();
    // console.log(app, '=========================');
  },
});

defineCustomElements();
